import React, { useEffect, useState } from 'react';
import { InputNumber, Modal, Select, Space, Popconfirm } from 'antd';
import TRNotification from '#/utils/notification';
import { imgString_3 } from '../../../../helper';
import styles from './index.less';
import _ from 'lodash';

const ModalComponent = ({ onPress, planYear, referencePowerData }: any) => {
  const [visible, setVisible] = useState(true),
    [show, setShow] = useState(false),
    [referencePowerOption, setReferencePowerOption] = useState<any>(),
    [referencePower, setReferencePower] = useState<any>(),
    [AdjustmentOption, setAdjustmentOption] = useState<any>(), //调整动作列表
    [Adjustment, setAdjustment] = useState<any>(0), //选中调整动作
    [value, setValue] = useState<any>(0), //输入的比例值
    [dataAll, setDataAll] = useState<any>([]), //全部参考表格数据
    [currentValue, setCurrentValue] = useState(0);
  useEffect(() => {
    setDataAll(_.cloneDeep(referencePowerData));
    const _temp: any = [];
    referencePowerData.forEach((t: any) => {
      const _year = t.title.split('年')[0];
      Object.keys(t).forEach((_t: any) => {
        if (_t.includes('plan')) {
          _temp.push({ label: _year + '年计划电量', value: _year + '_' + _t });
        }
        if (_t.includes('settlement')) {
          _temp.push({ label: _year + '年结算电量', value: _year + '_' + _t });
        }
        if (_t.includes('operate')) {
          _temp.push({ label: _year + '年经营电量', value: _year + '_' + _t });
        }
        if (_t.includes('guoneng')) {
          _temp.push({ label: _year + '年国能日新预测电量', value: _year + '_' + _t });
        }
        if (_t.includes('huineng')) {
          _temp.push({ label: _year + '年金风慧能预测电量', value: _year + '_' + _t });
        }
      });
    });
    setReferencePowerOption(_temp);
    setAdjustmentOption([
      { label: '上调', value: 0 },
      { label: '下调', value: 1 },
    ]);
  }, []);
  useEffect(() => {
    if (!referencePower) return;
    let data = 0;
    dataAll.forEach((t: any) => {
      if (t.title.includes(referencePower.split('_')[0])) {
        data = t[referencePower.split('_')[1]];
      }
    });
    if (Adjustment === 0) {
      data = parseFloat(
        parseFloat(((value / 100) * data + parseFloat(data as any)) as any).toFixed(1),
      );
    } else {
      data = parseFloat(
        parseFloat((parseFloat(data as any) - (value / 100) * data) as any).toFixed(1),
      );
    }
    setCurrentValue(data);
  }, [referencePower, Adjustment, value]);
  const _title = () => {
    return (
      <div className={styles.title}>
        <img src={imgString_3} />
        <div className={styles.iconText}>按比例制定计划</div>
      </div>
    );
  };

  const _onCancel = () => {
    if (referencePower || value) {
      setShow(true);
      return;
    }
    setVisible(false);
    onPress({ index: 0 });
  };

  const _onOk = () => {
    const _temp: any = {
      index: 1,
      value: currentValue,
    };
    onPress(_temp);
  };

  const onInputChange = (data: any) => {
    setValue(data);
  };
  const onPowerchange = (e: any) => {
    setReferencePower(e);
  };
  const onConfirm = () => {
    setVisible(false);
    onPress({ index: 0 });
  };
  return (
    <Modal
      width={696}
      className={styles.modal}
      visible={visible}
      centered={true}
      maskClosable={true}
      title={_title()}
      onCancel={_onCancel}
      cancelText={
        <Popconfirm
          placement="top"
          visible={show}
          onCancel={(e) => {
            e?.stopPropagation();
            setShow(false);
          }}
          title={'提示：当前工作将不被保存，继续执行此操作？'}
          onConfirm={onConfirm}
          okText="确认"
          cancelText="取消"
        >
          取消
        </Popconfirm>
      }
      okText={'确定'}
      onOk={_onOk}
    >
      <Space size={[12, 8]} wrap>
        <Select style={{ width: 120, fontSize: 12 }} value={planYear} disabled />
        <Select
          value={referencePower}
          style={{ width: 120 }}
          placeholder="选择参考电量"
          options={referencePowerOption}
          onChange={(e) => {
            onPowerchange(e);
          }}
        />
        <Select
          value={Adjustment}
          style={{ width: 120, fontSize: 12 }}
          placeholder="上调"
          options={AdjustmentOption}
          onChange={(e) => {
            setAdjustment(e);
          }}
        />
        <InputNumber
          value={value}
          style={{ width: 120, fontSize: 12 }}
          defaultValue={value}
          min={0}
          max={100}
          step={0.1}
          formatter={(val) => `${val}%`}
          parser={(val) => val!.replace('%', '')}
          onChange={onInputChange}
        />
      </Space>
      <div className={styles.cell}>
        <span className={styles.title}>
          {planYear}年计划电量<span className={styles.unit}>{currentValue} MWh</span>
        </span>
      </div>
    </Modal>
  );
};
class AdjustScale {
  __key__ = '';

  show = (props: any) => {
    return new Promise((resolve) => {
      if (this.__key__ !== '') return;
      this.__key__ = String(Date.now());
      TRNotification.add({
        key: this.__key__,
        content: (
          <ModalComponent
            {...props}
            onPress={(result: any) => {
              TRNotification.remove(this.__key__);
              this.__key__ = '';
              resolve(result);
            }}
          />
        ),
        duration: null,
      });
    });
  };

  dismiss = () => {
    if (this.__key__.length > 0) {
      TRNotification.remove(this.__key__);
      this.__key__ = '';
    }
  };
}

export default new AdjustScale();
